<template>
  <div>
    <!-- 条件筛选 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card shadow="always">
          <el-form :inline="true" :model="queryForm" ref="queryForm" class="demo-form-inline">
            <el-form-item label="用户名" prop="userName">
              <el-input v-model="queryForm.userName" placeholder="用户名"></el-input>
            </el-form-item>
            <el-form-item label="手机号" prop="userPhone">
              <el-input v-model="queryForm.userPhone" placeholder="手机号"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="userEmail">
              <el-input v-model="queryForm.userEmail" placeholder="邮箱"></el-input>
            </el-form-item>
            <el-form-item label="是否冻结" prop="forbid">
              <el-select v-model="queryForm.forbid" placeholder="是否冻结">
                <el-option label="是" value="0"></el-option>
                <el-option label="否" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="内部人员" prop="interior">
              <el-select v-model="queryForm.interior" placeholder="内部人员">
                <el-option label="是" value="0"></el-option>
                <el-option label="否" value="1"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="roles">
              <el-select v-model="queryForm.roles" multiple collapse-tags placeholder="请选择">
                <el-option v-for="item in options"
                           :key="item.value" :label="item.label" :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="生日" prop="birthdays">
              <el-date-picker
                v-model="queryForm.birthdays"
                type="daterange"
                value-format="yyyy-MM-ddTHH:mm:ss.000Z"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="warning" @click="resetForm('queryForm')">重置</el-button>
              <el-button type="primary" @click="onSubmit">查询</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <br>

    <!-- 按钮操作 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card shadow="always" style="text-align: left">
          <el-button type="primary" size="small" @click="addOrUpdate('')">新增用户</el-button>
          <el-button type="danger" size="small" @click="batchDel">批量删除</el-button>
        </el-card>
      </el-col>
    </el-row>

    <br>

    <!-- 数据列表 -->
    <el-row :gutter="24">
      <el-col :span="24">
        <el-card shadow="always">
          <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="50"></el-table-column>
            <el-table-column prop="userName" label="用户名" sortable></el-table-column>
            <el-table-column label="头像" width="100px">
              <template slot-scope="scope">
                <el-image style="width: 50px; height: 50px"
                          :src="'http://localhost:7000/admin/file/download?fileName='+scope.row.userImg">
                  <div slot="error" class="image-slot" v-if="scope.row.userImg == null">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </template>
            </el-table-column>
            <el-table-column prop="userPhone" label="手机号"></el-table-column>
            <el-table-column prop="userEmail" label="邮箱"></el-table-column>
            <el-table-column prop="interior" label="内部人员" width="100px">
              <template slot-scope="scope">
                <span>{{ scope.row.interior === 0?'是' :'否'}}</span>
              </template>
            </el-table-column>
            <el-table-column prop="forbid" label="是否冻结" width="100px">
              <template slot-scope="scope">
                <el-switch v-model="scope.row.forbid" disabled
                           :active-value=0 :inactive-value=1
                           active-color="#ff4949" inactive-color="#13ce66"></el-switch>
              </template>
            </el-table-column>
            <el-table-column prop="roles" label="角色">
              <template slot-scope="scope">
                <el-tag v-for="(role,index) in scope.row.roles" :key="index" type="success">{{ role }}&nbsp;</el-tag>
              </template>

            </el-table-column>
            <el-table-column prop="birthday" label="生日" sortable :formatter="dateFormat"></el-table-column>
            <el-table-column label="操作" width="130">
              <template slot-scope="scope">
                <el-button type="text" size="small" @click="handleClick(scope.row)">查看</el-button>
                <el-button type="text" size="small" @click="addOrUpdate(scope.row.id)">编辑</el-button>
                <el-button type="text" size="small" @click="delData(scope.row.id)">删除</el-button>
                <el-button type="text" size="small" @click="addRole(scope.row.id)">赋予角色</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="block" style="margin-top: 10px; text-align: right">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="dataCount">
            </el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加或修改 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" style="text-align: left;">
      <el-form :model="addForm" :rules="rules" ref="addForm">
        <el-form-item label="用户名" prop="userName" :label-width="formLabelWidth">
          <el-input v-model="addForm.userName" autocomplete="off" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="userPhone" :label-width="formLabelWidth">
          <el-input v-model="addForm.userPhone" autocomplete="off" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail" :label-width="formLabelWidth">
          <el-input v-model="addForm.userEmail" autocomplete="off" style="width: 220px;"></el-input>
        </el-form-item>
        <el-form-item label="内部人员" prop="interior" :label-width="formLabelWidth">
          <el-select v-model="addForm.interior" placeholder="请选择">
            <el-option label="是" :value="0"></el-option>
            <el-option label="否" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否冻结" prop="forbid" :label-width="formLabelWidth">
          <el-switch v-model="addForm.forbid"
                     :active-value=0 :inactive-value=1
                     active-color="#ff4949" inactive-color="#13ce66"></el-switch>
        </el-form-item>
        <el-form-item label="生日" prop="birthday" :label-width="formLabelWidth">
          <el-date-picker v-model="addForm.birthday"
                          type="date" value-format="yyyy-MM-dd"
                          placeholder="选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="头像" prop="userImg" :label-width="formLabelWidth">
          <el-upload action="http://localhost:7000/admin/file/upload"
                     list-type="picture-card" name="file" :disabled="uploadDisabled"
                     :on-success="uploadSuccess" ref="upload" :file-list="imgList">
            <i slot="default" class="el-icon-plus"></i>
            <div slot="file" slot-scope="{file}">
              <img class="el-upload-list__item-thumbnail" :src="file.url" ref="prodImg">
              <span class="el-upload-list__item-actions">
                <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
                  <i class="el-icon-zoom-in"></i>
                </span>
                <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                  <i class="el-icon-delete"></i>
                </span>
              </span>
            </div>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>
        <el-form-item label="备注" prop="desc" :label-width="formLabelWidth">
          <el-input type="textarea" v-model="addForm.desc"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('addForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('addForm')" :loading="saveLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 赋予角色 -->
    <el-dialog title="赋予角色" :visible.sync="addRoleShow" style="text-align: left" :before-close="closeAddRole">
      <el-select v-model="roles" multiple style="margin-left: 20px;" placeholder="请选择">
        <el-option v-for="item in options" :key="item.value"
                   :label="item.label" :value="item.value">
        </el-option>
      </el-select>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddRole()" :loading="saveLoading">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import {get, post} from '@/api/http.js'
  import * as fecha from 'element-ui/lib/utils/date';

  export default {
    name: "user",

    // 页面加载就执行
    mounted: function () {
      this.getListData();
      this.getRoles();
      // 设置面包屑
      this.$store.commit("setBreadcrumbItems", ['系统', '用户管理']);
    },

    // 双向数据绑定
    data() {
      // 可以声明一个方法进行调用
      // 校验手机号
      let checkPhone = (rule, value, callback) => {
        const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/;
        if (!value) {
          return callback(new Error('电话号码不能为空'))
        }
        setTimeout(() => {
          if (!Number.isInteger(+value.trim())) {
            callback(new Error('请输入数字值'))
          } else {
            if (phoneReg.test(value)) {
              callback()
            } else {
              callback(new Error('电话号码格式不正确'))
            }
          }
        }, 100)
      };
      return {
        // 表单数据邦迪
        queryForm: {
          userName: '',
          userPhone: '',
          userEmail: '',
          forbid: '',
          interior: '',
          birthdays: [],
          roles: '',
          current: 1,
          size: 10,
          sortBy: '',
          sortOrder: ''
        },

        // 角色下拉数据
        options: [],

        // 表格数据
        tableData: [],

        // 列表多选数据ID集合
        selectIds: [],

        // 分页参数
        currentPage: 1,
        pageSize: 10,
        dataCount: 0,

        // 添加或修改弹出框
        title: '添加用户',
        bizId: '',
        dialogFormVisible: false,
        formLabelWidth: '120px',
        addForm: {
          userName: '',
          userEmail: '',
          userPhone: '',
          interior: '',
          forbid: 1,
          birthday: '',
          userImg: '',
          desc: ''
        },
        // 表单校验
        rules: {
          userName: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur'}
          ],
          userPhone: [
            {required: true, message: '请输入手机号', trigger: 'blur'},
            {validator: checkPhone, message: '请输入正确手机号格式', trigger: ['blur', 'change']}
          ]
        },
        // 添加或修改数据保存loading
        saveLoading: false,

        // 上传图片参数
        uploadDisabled: false,
        // 图片查看大图参数
        dialogImageUrl: '',
        dialogVisible: false,

        // 图片文件列表
        imgList: [],

        // 赋予角色
        addRoleShow: false,
        roles: []

      }
    },

    // 方法区
    methods: {
      // 日期格式转换
      dateFormat(row, column, cellValue) {
        return cellValue ? fecha.format(new Date(cellValue), 'yyyy-MM-dd') : '';
      },

      // 关闭添加角色回调
      closeAddRole(done) {
        this.bizId = '';
        this.roles = [];
        done()
      },

      // 执行添加角色
      submitAddRole() {
        if (this.roles.length === 0) {
          this.$message({
            message: '请至少选中一个角色',
            type: 'warning'
          });
          return;
        }
        let param = {id: this.bizId, roles: this.roles.toString()};
        get("/admin/user/addRole", param)
          .then(res => {
            this.$message({
              message: '角色赋予成功',
              type: 'success'
            });
            this.addRoleShow = false;
            this.bizId = '';
            this.roles = [];
            this.getListData();
          })
          .catch(err => {
            this.$message({
              message: '角色赋予失败',
              type: 'error'
            });
          })
      },

      // 赋予角色
      addRole(id) {
        this.bizId = id;
        this.addRoleShow = true;

        // 赋予角色之前进行回显
        get('/admin/user/getRole/' + id, '')
          .then(res => {
            this.roles = res.data;
          });
      },

      // 提交添加表单
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          // 表单验证是否通过
          if (valid) {
            this.saveLoading = true;
            let uri = "";
            let msg = "";
            if (this.bizId === '') {
              uri = "/admin/user/add";
              msg = "恭喜你，用户添加";
            } else {
              uri = "/admin/user/update";
              msg = "恭喜你，用户修改";
            }
            // 发起请求
            post(uri, this.addForm)
              .then(res => {
                this.$message({
                  message: msg + '成功',
                  type: 'success'
                });
              })
              .catch(err => {
                this.$message({
                  message: msg + '失败',
                  type: 'error'
                });
              })
              .finally(() => {  // 请求响应之后在执行
                this.saveLoading = false;
                // 关闭添加或修改弹出出框
                this.dialogFormVisible = false;
                this.bizId = '';
                this.resetForm('addForm');
                this.getListData();
              })
          } else {
            return false;
          }
        });
      },

      // 上传成功回调
      uploadSuccess(response, file, fileList) {
        this.addForm.userImg = response.data.fileName;
        this.uploadDisabled = true;
      },

      // 移除图片
      handleRemove(file) {
        this.uploadDisabled = false;
        let fileList = this.$refs.upload.uploadFiles;
        let index = fileList.findIndex(fileItem => {
          return fileItem.uid === file.uid
        });
        fileList.splice(index, 1);
      },

      // 查看大图
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },

      // 提交查询表单
      onSubmit() {
        this.getListData();
      },

      // 重置表单
      resetForm(formName) {
        this.dialogFormVisible = false;
        this.bizId = '';
        this.$refs[formName].resetFields();
      },

      // 添加或修改弹出对话框
      addOrUpdate(id) {
        this.bizId = id;
        this.dialogFormVisible = true;
        if (id !== '') {
          this.title = "修改用户";
          get("/admin/user/get/" + id, '')
            .then(res => {
              this.addForm = res.data;
            })
            .catch(err => {

            })
            .finally(() => {

            })
        }
      },

      // 表格数据多选,获取ID
      handleSelectionChange(val) {
        // val 传给的是数组，里面放的是选中当前行的所有数据
        // console.info(val);
        // 声明一个空数组，将val遍历获取每一行数据的ID，放入集合
        let idsArr = new Array();
        val.forEach(row => {
          idsArr.push(row.id)
        });
        // 赋值给全局变量
        this.selectIds = idsArr;
      },

      // 批量删除
      batchDel() {
        if (this.selectIds.length === 0) {
          this.$message({
            type: 'warning',
            message: '请至少选择一条数据'
          });
          return;
        }
        // 调用删除方法
        this.delData(this.selectIds.toString());
      },

      // 删除数据
      delData(id) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let param = {ids: id};
          get('/admin/user/del2', param)
            .then(res => {
              this.$message({
                type: 'success',
                message: '删除成功'
              });
            })
            .catch(err => {
              this.$message({
                type: 'error',
                message: '删除失败'
              });
            }).finally(() => {
            this.getListData();
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      // 分页组件参数变动
      handleSizeChange(val) {
        this.queryForm.size = val;
        this.getListData();
      },
      handleCurrentChange(val) {
        this.queryForm.current = val;
        this.getListData();
      },

      // 获取列表数据
      getListData() {
        post("/admin/user/list", this.queryForm)
          .then(res => {
            this.tableData = res.data.records;
            this.dataCount = res.data.total;
            this.pageSize = res.data.size;
            this.currentPage = res.data.current;
          })
          .catch(err => {

          })
          .finally(() => {

          })
      },

      // 获取角色数据
      getRoles() {
        get("/admin/role/info", '')
          .then(res => {
            this.options = res.data;
          })
          .catch(err => {

          })
      }
    }
  }
</script>

<style scoped>

</style>
